// runtime.requestPermissions(["access_fine_location","access_coarse_location"]);
/**
 * @author Mr_老冷QQ1920712147
 * @description WIFI控制模块
 */
importPackage(java.lang);
importPackage(android.net);
importPackage(android.net.wifi);

importClass(android.os.Build);
importClass(android.os.PatternMatcher);

importClass(java.util.List);
importClass(java.util.ArrayList);

importClass(android.content.pm.PackageManager);
importClass(android.content.Context);


module.exports = (function () {
    let WifiUtils = {};

    var mWifiManager = context.getSystemService(Context.WIFI_SERVICE);
    /**
     * @description WIFI是否连接
     * @return {string|null}
     */
    WifiUtils.isConnectedWifi = function () {
        if (mWifiManager.isWifiEnabled()) {
            var connectedWifiInfo = mWifiManager.getConnectionInfo();
            if (connectedWifiInfo.SSID != "<unknown ssid>") {
                return connectedWifiInfo.SSID;
            }
        }
        return null;
    }
    /**
     * @description WIFI是否打开
     * @return {boolean}
     */
    WifiUtils.isWifiEnable = function () {
        let isEnable = false;
        if (mWifiManager != null) {
            if (mWifiManager.isWifiEnabled()) {
                isEnable = true;
            }
        }
        return isEnable;
    }
    /**
     * @description 连接WIFI
     */
    WifiUtils.openWifi = function () {
        if (mWifiManager != null && !WifiUtils.isWifiEnable()) {
            mWifiManager.setWifiEnabled(true);
        }
    }
    /**
     * @description 关闭WIFI
     */
    WifiUtils.closeWifi = function () {
        if (mWifiManager != null && WifiUtils.isWifiEnable()) {
            mWifiManager.setWifiEnabled(false);
        }
    }
    /**
     * @description 获取WIFI列表
     * @return {java.util.ArrayList}
     */
    WifiUtils.getWifiList = function () {
        let resultList = new java.util.ArrayList();
        if (mWifiManager != null && WifiUtils.isWifiEnable()) {
            resultList.addAll(mWifiManager.getScanResults());
        }
        return resultList;
    }
    /**
     * @description 通过密码连接WIFI
     * @param ssid WIFI名
     * @param pws WIFI密码
     */
    WifiUtils.connectWifiPws = function (ssid, pws) {
        if (Build.VERSION.SDK_INT >= 29) {
            let specifier = new WifiNetworkSpecifier.Builder()
                .setSsidPattern(new PatternMatcher(ssid, PatternMatcher.PATTERN_PREFIX))
                .setWpa2Passphrase(pws)
                .build();
            let request = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .setNetworkSpecifier(specifier)
                .build();
            let connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE);
            let networkCallback = new JavaAdapter(android.net.ConnectivityManager.NetworkCallback, {
                onAvailable: function (network) {
                    // log("连接成功了")
                },
                onUnavailable: function () {
                    // log("用户取消了连接");
                }
            })
            connectivityManager.requestNetwork(request, networkCallback);

            return;
        }
        //低于SDKINT 29的 系统
        mWifiManager.disableNetwork(mWifiManager.getConnectionInfo().getNetworkId());
        let netId = mWifiManager.addNetwork(getWifiConfig(ssid, pws, true));
        mWifiManager.enableNetwork(netId, true);
    }
    /**
     * @description 不通过密码连接WIFI
     * @param ssid
     */
    WifiUtils.connectWifiNoPws = function (ssid) {
        mWifiManager.disableNetwork(mWifiManager.getConnectionInfo().getNetworkId());
        let netId = mWifiManager.addNetwork(getWifiConfig(ssid, "", false));
        mWifiManager.enableNetwork(netId, true);
    }

    /**
     * @description 获取WIFI配置信息
     * @param ssid
     * @param pws
     * @param isHasPws
     * @return {WifiConfiguration}
     */
    function getWifiConfig(ssid, pws, isHasPws) {
        let config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";

        let tempConfig = isExist(ssid);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }
        if (isHasPws) {
            config.preSharedKey = "\"" + pws + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        } else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        return config;
    }

    /**
     * @description 指定WIFI名是否存在
     * @param ssid
     * @return {null|*}
     */
    function isExist(ssid) {
        let configs = new java.util.ArrayList();
        configs.addAll(mWifiManager.getConfiguredNetworks());
        for (let i = 0; i < configs.size(); i++) {
            let config = configs.get(i);
            if (config.SSID.equals("\"" + ssid + "\"")) {
                return config;
            }
        }
        return null;
    }

    /**
     * 以下是连接代理的方法,自己测试
     */
    function setEnumField(obj, value, name) {
        let f = obj.getClass().getField(name);
        f.set(obj, Enum.valueOf(f.getType(), value));
    }

    function getDeclaredFieldObject(obj, name) {
        let f = obj.getClass().getDeclaredField(name);
        f.setAccessible(true);
        let out = f.get(obj);
        return out;
    }

    function setDeclardFildObject(obj, name, object) {
        let f = null;
        try {
            f = obj.getClass().getDeclaredField(name);
        } catch (e) {
            log(e);
        }
        f.setAccessible(true);
        try {
            f.set(obj, object);
        } catch (e) {
            log(e);
        }
    }

    // 获取当前的Wifi连接
    WifiUtils.getCurrentWifiConfiguration = function () {
        if (!mWifiManager.isWifiEnabled())
            return null;
        let configurationList = mWifiManager.getConfiguredNetworks();
        let configuration = null;
        let cur = mWifiManager.getConnectionInfo().getNetworkId();

        for (let i = 0; i < configurationList.size(); ++i) {
            let wifiConfiguration = configurationList.get(i);
            if (wifiConfiguration.networkId == cur)
                configuration = wifiConfiguration;
        }
        return configuration;
    }
    WifiUtils.isProxyed = function () {
        let config = WifiUtils.getCurrentWifiConfiguration();
        if (config.proxySettings == "NONE") {
            return false;
        }
        return true;
    }
    WifiUtils.setHttpPorxySetting = function (host, port) {
        let config = WifiUtils.getCurrentWifiConfiguration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mInfo = ProxyInfo.buildDirectProxy(host, port);
        }
        if (config != null) {
            let clazz = Class.forName("android.net.wifi.WifiConfiguration");
            let parmars = Class.forName("android.net.ProxyInfo");
            let method = clazz.getMethod("setHttpProxy", parmars);
            method.invoke(config, mInfo);
            let mIpConfiguration = getDeclaredFieldObject(config, "mIpConfiguration");

            setEnumField(mIpConfiguration, "STATIC", "proxySettings");
            setDeclardFildObject(config, "mIpConfiguration", mIpConfiguration);
            mWifiManager.updateNetwork(config);
            mWifiManager.disconnect();
            mWifiManager.reconnect();
        }
    }

    WifiUtils.unSetHttpProxy = function () {
        let configuration = WifiUtils.getCurrentWifiConfiguration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mInfo = ProxyInfo.buildDirectProxy(null, 0);
        }
        if (configuration != null) {
            let clazz = Class.forName("android.net.wifi.WifiConfiguration");
            let parmars = Class.forName("android.net.ProxyInfo");
            let method = clazz.getMethod("setHttpProxy", parmars);
            method.invoke(configuration, mInfo);

            let mIpConfiguration = getDeclaredFieldObject(configuration, "mIpConfiguration");
            setEnumField(mIpConfiguration, "NONE", "proxySettings");
            setDeclardFildObject(configuration, "mIpConfiguration", mIpConfiguration);

            //保存设置
            mWifiManager.updateNetwork(configuration);
            mWifiManager.disconnect();
            mWifiManager.reconnect();
        }
    }

    return WifiUtils;
})()